<?php
namespace app\queue\redis;

use Webman\RedisQueue\Consumer; 
use support\Log;
use Webman\RedisQueue\Redis;
use Webman\RedisQueue\Client;

class PankouConsumer implements Consumer
{
    // 要消费的队列名 
    public $queue = 'history_trade';
    
    // Redis连接配置
    public $connection = 'default';
    
    // 消费逻辑
    public function consume($data)
    {
        try {    
            $start_time = microtime(true);
            $code = $data['code']; 
            //秒级成交量
            $sortSetKey = "second:chengjiaoliang:".date('Y-m-d').":top";
            //秒级成交量
            $sortSetKey10000 = "second:chengjiaoliang:".date('Y-m-d').":10000:top";   
      
            $response =  self::getBaseXueQiuCurl($code);
            Log::info("history_trade 返回数据: $response");
            $result1 = json_decode($response,true);
          
            if(isset($result1['data'])){
                $allStocks = $result1['data']['items'];
                foreach ($allStocks as $stocks){
                    $result = [
                        'code' => $stocks['symbol'],
                        'price' => $stocks['current'],
                        'times' => date("Y-m-d H:i:s", $stocks['timestamp']/1000),
                        'trade_volume' =>  $stocks['trade_volume']/100,
                        'real_time' =>date("Y-m-d H:i:s")
                    ];
                    $code = $stocks['symbol']; 
                    $hashCodeKey = "second:chengjiaoliang:".date('Y-m-d').":".$code;
                    $hashKey = date("Y-m-d H:i:s", $stocks['timestamp']/1000);
                    $times = $stocks['trade_volume']/100;
                    $name = $code.":".date("H:i:s", $stocks['timestamp']/1000);
                    if(!Redis::zScore($sortSetKey10000, $name) && $times >= 10000){
                        Redis::zAdd($sortSetKey10000, $times, $name);
                        //发送邮件
                        Client::send('email_send', $stocks);
                    }
                    //记录出现万手的股票
                    if(!Redis::zScore($sortSetKey, $name)){
                        Redis::zAdd($sortSetKey, $times, $name);
                    }
                    //hash
                    if(!Redis::hExists($hashCodeKey, $hashKey)){
                        Redis::hSet($hashCodeKey, $hashKey, $times);
                    }
                }  
            }
            echo date("Y-m-d H:i:s")."【history_trade】-处理{$code}成功"."\r\n"; 
            Log::info("盘口交易处理成功: $code 耗时：".(microtime(true)- $start_time));
            return true; 
        } catch (\Throwable $e) {
            Log::error("盘口交易处理失败: {$e->getLine()}  {$e->getMessage()}");
            return false; // 触发重试
        }
    } 
    
    /**
     * 爬虫记录
     * @param unknown $code
     * @return mixed
     */
    public static function getBaseXueQiuCurl($code) {
        $url = "https://stock.xueqiu.com/v5/stock/history/trade.json?symbol=$code&count=10";
        $ch = curl_init ();
        $header [] = "Host: stock.xueqiu.com";
        $header [] = "Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4";
        $header [] = "Cookie: xq_a_token=abfd9c65d471bdcdac59a60cf0194d3590d3285d;xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOjEwMzU3NDY4MDUsImlzcyI6InVjIiwiZXhwIjoxNzQ1NTYzMjE4LCJjdG0iOjE3NDI5NzE3MjkwMjQsImNpZCI6Ikp0WGJhTW43ZVAifQ.isvglkTj-HtlzlHvHqePMP-pSWqFapRlhain8T5XlxGKUH-BsUbt235NFLC9Qz10m9olW2W_mTEz-tLajleAxJO8FugKVqpUOZoUL08fiXwDxkbj1Fr-g7GNdiO6yFIeiFBvFTvVz2H5Tjj1O0vodvzKQF7U39Ai5qhhufRptafkMYUwcnfQcToWnKxka7O5UTVl_ysRoq5bPcyRuJ63uhb3DhconxIxVQ37KODwNz1fnWEKjIKiFK9gUqd-cbkRTOJpPGWZ2M1KfpeP3FE5RhyEQB8QGBjKviYMhFW-adQXzh2aS-DX3eQVObrrVUSw25ZwKmCNy-t1W1MykYqqzw;u=1035746805;session_id=;xid=0";
        $header [] = "X-Device-ID: 1XIAOMIdbdbe53579ad35347ace0e8848be9efe";
        $header [] = "X-Device-Model-Name: HUAWEI_TAS-AN00";
        $header [] = "X-Device-OS: Android 9";
        $header [] = "Accept-Encoding: gzip";
        $header [] = "Connection: Keep-Alive";
        
        $xforip = rand ( 1, 254 ) . "." . rand ( 1, 254 ) . "." . rand ( 1, 254 ) . "." . rand ( 1, 254 );
        $header [] = "X-FORWARDED-FOR: $xforip";
        $header [] = "CLIENT-IP: $xforip";
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt ( $ch, CURLOPT_ENCODING, "" );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 3 ); // 设置1秒超时
        curl_setopt ( $ch, CURLOPT_USERAGENT, "Xueqiu Android 14.25" );
        $output = curl_exec ( $ch );
        // $output = mb_convert_encoding($output, 'utf-8', 'GBK,UTF-8,ASCII');
        curl_close ( $ch );
        return $output;
    } 
} 